package com.skit.widget

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import kotlinx.android.synthetic.main.editext_layout.view.*

class EditText : FrameLayout {
    private lateinit var view: View

    constructor(context: Context) : this(context, null)

    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr,
        0
    )

    constructor(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        view = LayoutInflater.from(context).inflate(R.layout.editext_layout, this, false)
        addView(view)
        attrsSet(attrs)
        widget_editText.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(p0: Editable?) {

            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                p0?.let {
                    clear.visibility = if (it.isNotEmpty()) {
                        View.VISIBLE
                    } else {
                        View.GONE
                    }
                }
            }

        })

        clear.setOnClickListener {
            widget_editText.setText("")
        }
    }

    private fun attrsSet(attrs: AttributeSet?) {
        context.obtainStyledAttributes(attrs, R.styleable.EditText).apply {
            getString(R.styleable.EditText_android_hint)?.let { widget_editText.hint = it }
            recycle()
        }
    }

    fun setText(c: CharSequence) {
        widget_editText.setText(c)
    }

    fun setText(text: String) {
        widget_editText.setText(text)
    }

    fun getText() = widget_editText.text.toString()

}